package CreationalPatterns.Prototype.Deep;

import java.io.*;

public class Goat implements Cloneable,Serializable {

  public String name;
  public GoatTarget goatTarget;

  public Goat() {
    super();
  }

//  方式一：
//  @Override
//  protected Object clone() throws CloneNotSupportedException {
//
//    Object gt = null;
////    对基本数据类型和String类型的处理
//    gt = super.clone();
////    对引用类型的处理
//    Goat goat = (Goat)gt;
//    goat.goatTarget = (GoatTarget) goatTarget.clone();
//
//    return goat;
//  }

//  方式二：
  @Override
  protected Object clone() throws CloneNotSupportedException {

    ByteArrayOutputStream bos = null;
    ByteArrayInputStream bis = null;
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;

    try {
//      序列化
      bos = new ByteArrayOutputStream();
      oos = new ObjectOutputStream(bos);
      oos.writeObject(this);//以流的形式将当前对象输出
//      反序列化
      bis = new ByteArrayInputStream(bos.toByteArray());
      ois = new ObjectInputStream(bis);
      Goat goat = (Goat) ois.readObject();

      return goat;

    }catch (Exception e){
      e.printStackTrace();
      return null;
    }finally {
      try {
        bos.close();
        bis.close();
        oos.close();
        ois.close();
      }catch (Exception e){
        e.printStackTrace();
      }
    }
  }
}
